//
//  MCMineAddBankCardViewController.m
//  TLYL
//
//  Created by miaocai on 2017/7/12.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCMineAddBankCardViewController.h"
#import "MCSelectedBottomView.h"
#import "MCBankModel.h"
#import "MCButton.h"
#import "MCAddBankCardModel.h"
#import "MCMineInfoModel.h"
#import "MCPasswordSettingViewController.h"
#import "MCMineInfoModel.h"
@interface MCMineAddBankCardViewController ()
<
MCSelectedBottomDelegate,
UITextFieldDelegate
>

@property (nonatomic,weak) UIButton *addBtn;
@property (nonatomic,weak) UITextField *nameTF;
@property (nonatomic,weak) MCSelectedBottomView * bottomView;

@property (nonatomic,weak)MCButton *shengSelectedBtn;
@property (nonatomic,weak)MCButton *citySelectedBtn;
@property (nonatomic,weak)MCButton *bankSelectedBtn;
//支行名称
@property (nonatomic,weak)UITextField *bankNameTf;

//银行卡号
@property (nonatomic,weak)UITextField *cardNumTf;

@property (nonatomic,strong)MCBankModel *bankModel;

@property (nonatomic,strong)MCAddBankCardModel * apiModel;
@property (nonatomic,strong)MCMineInfoModel *mineInfoModel;


@property (nonatomic,strong)NSString *UserRealName;
@end

@implementation MCMineAddBankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"添加银行卡";
    [self setUpUI];
   
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;

}

- (void)setUpUI{
    UIButton * btn=[[UIButton alloc]initWithFrame:self.view.bounds];
    btn.backgroundColor=[UIColor clearColor];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(closeKeyboard) forControlEvents:UIControlEventTouchUpInside];
    
    _bankModel=[[MCBankModel alloc]init];
    
    self.view.backgroundColor=RGB(239, 246, 252);
    
    /********************1*********************/
    UIView * view1=[[UIView alloc]init];
    [self.view addSubview:view1];
    view1.backgroundColor=[UIColor whiteColor];
    
    
    MCMineInfoModel * mineInfoModel=[MCMineInfoModel sharedMCMineInfoModel];
    CGFloat Top=0;
    //如果该用户已经绑定过姓名   则不需要输入
    if (mineInfoModel.UserRealName.length>0) {
        _UserRealName=mineInfoModel.UserRealName;
        view1.frame=CGRectMake(0, 0, G_SCREENWIDTH, 45);
    }else{
        view1.frame=CGRectMake(0, 0, G_SCREENWIDTH, 90);
        
        UILabel *nameLabel = [[UILabel alloc] init];
        [view1 addSubview:nameLabel];
        nameLabel.text = @"姓名";
        nameLabel.textColor = MC_SKYBLUE_COLOR;
        nameLabel.font = [UIFont systemFontOfSize:14];
        nameLabel.frame=CGRectMake(10, 0, 50, 45);
        
        UITextField *nameTf = [[UITextField alloc] init];
        [self setTextField:nameTf WithPlaceholder:@"请输入持卡人姓名" and:UIKeyboardTypeDefault];
        [view1 addSubview:nameTf];
        nameTf.frame=CGRectMake(60, 0, G_SCREENWIDTH-70, 45);
        _nameTF=nameTf;
        _nameTF.tag=10001;
        
        UIView *lineView1 = [[UIView alloc] init];
        lineView1.backgroundColor = MC_SEPAETOR_COLOR;
        [view1 addSubview:lineView1];
        lineView1.frame=CGRectMake(0, 45, G_SCREENWIDTH, 0.5);
        
        Top=45;
        
    }
    

    
    UILabel *bankLabel = [[UILabel alloc] init];
    [view1 addSubview:bankLabel];
    bankLabel.text = @"银行";
    bankLabel.textColor = MC_SKYBLUE_COLOR;
    bankLabel.font = [UIFont systemFontOfSize:14];
    bankLabel.frame=CGRectMake(10,Top, 50, 45);
    
    MCButton *bankSelectedBtn = [[MCButton alloc] init];
    [view1 addSubview:bankSelectedBtn];
    [bankSelectedBtn addTarget:self action:@selector(bankSelectedBtnClick) forControlEvents:UIControlEventTouchDown];
    [bankSelectedBtn setTitle:@"请选择银行 >" forState:UIControlStateNormal];
    bankSelectedBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [bankSelectedBtn setTitleColor:RGB(68, 68, 68) forState:UIControlStateNormal];
    bankSelectedBtn.frame=CGRectMake(60, Top, G_SCREENWIDTH-70, 45);
    _bankSelectedBtn=bankSelectedBtn;
    
    /********************2*********************/
    UIView * view2=[[UIView alloc]init];
    [self.view addSubview:view2];
    view2.backgroundColor=[UIColor whiteColor];
    view2.frame=CGRectMake(0, 45+Top+10, G_SCREENWIDTH, 45);
    
    MCButton *shengSelectedBtn = [[MCButton alloc] init];
    [view2 addSubview:shengSelectedBtn];
    [shengSelectedBtn setTitle:@"请选择省份 >" forState:UIControlStateNormal];
    [shengSelectedBtn addTarget:self action:@selector(shengSelectedBtnClick) forControlEvents:UIControlEventTouchDown];
    shengSelectedBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [shengSelectedBtn setTitleColor:RGB(68, 68, 68) forState:UIControlStateNormal];
    shengSelectedBtn.frame=CGRectMake(10, 0, G_SCREENWIDTH/2.0-20, 45);
    _shengSelectedBtn=shengSelectedBtn;
    
    
    UIView * viewLine=[[UIView alloc]init];
    [view2 addSubview:viewLine];
    viewLine.backgroundColor= RGB(239, 246, 252);
    viewLine.frame=CGRectMake(G_SCREENWIDTH/2.0, 0, 0.5, 45);
    
    MCButton *citySelectedBtn = [[MCButton alloc] init];
    [view2 addSubview:citySelectedBtn];
    [citySelectedBtn setTitle:@"请选择市区 >" forState:UIControlStateNormal];
    citySelectedBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [citySelectedBtn addTarget:self action:@selector(citySelectedBtnClick) forControlEvents:UIControlEventTouchDown];
    [citySelectedBtn setTitleColor:RGB(68, 68, 68) forState:UIControlStateNormal];
    citySelectedBtn.frame=CGRectMake(G_SCREENWIDTH/2.0+10, 0, G_SCREENWIDTH/2.0-20, 45);
    _citySelectedBtn=citySelectedBtn;
    
    /********************3*********************/
    UIView *view3=[[UIView alloc]init];
    [self.view  addSubview:view3];
    view3.backgroundColor=[UIColor whiteColor];
    view3.frame=CGRectMake(0, 45+Top+10+45+10, G_SCREENWIDTH, 90);
    
   
    UITextField *bankNameTf = [[UITextField alloc] init];
    [self setTextField:bankNameTf WithPlaceholder:@"请输入支行名称" and:UIKeyboardTypeDefault];
    [view3 addSubview:bankNameTf];
    bankNameTf.frame=CGRectMake(10, 0, G_SCREENWIDTH-20-50, 45);
    _bankNameTf=bankNameTf;
    _bankNameTf.tag=10002;
    UILabel *tipLab =[[UILabel alloc]initWithFrame:CGRectZero];
    tipLab.textColor=RGB(69, 142, 226);
    tipLab.font=[UIFont systemFontOfSize:12];
    tipLab.text =@"(选填)";
    tipLab.textAlignment=NSTextAlignmentRight;
    [view3 addSubview:tipLab];
    tipLab.frame=CGRectMake(G_SCREENWIDTH-60, 0, 50, 45);
    
    UIView * viewLine2=[[UIView alloc]init];
    [view3 addSubview:viewLine2];
    viewLine2.backgroundColor= RGB(239, 246, 252);
    viewLine2.frame=CGRectMake(0, 45, G_SCREENWIDTH, 0.5);
    
    UITextField *cardNumTf = [[UITextField alloc] init];
    [self setTextField:cardNumTf WithPlaceholder:@"请输入银行卡号" and:UIKeyboardTypeNumberPad];
    [view3 addSubview:cardNumTf];
    cardNumTf.frame=CGRectMake(10, 45, G_SCREENWIDTH-20, 45);
    _cardNumTf=cardNumTf;
    _cardNumTf.tag=10003;
    _cardNumTf.delegate=self;

    
    UIButton *addBtn = [[UIButton alloc] init];
    [self setFooter:addBtn];
    [self.view addSubview:addBtn];
    addBtn.frame=CGRectMake(10, 275, G_SCREENWIDTH-20, 50);

    MCSelectedBottomView * bottomView=[[MCSelectedBottomView alloc]init];
    [self.view addSubview:bottomView];
    _bottomView=bottomView;
    _bottomView.delegate=self;
    bottomView.frame=CGRectMake(0, G_SCREENHEIGHT, G_SCREENWIDTH, 0.0);
    
    
    
    
    
//    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
//    singleTapGesture.numberOfTapsRequired = 1;
//    singleTapGesture.cancelsTouchesInView = NO;
//    [self.view  addGestureRecognizer:singleTapGesture];
    
    

}



-(void)setTextField:(UITextField*)textField WithPlaceholder:(NSString *)placeholder and:(UIKeyboardType)type{
    textField.placeholder=placeholder;
    textField.borderStyle = UITextBorderStyleNone;
    textField.backgroundColor=[UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:14];
    textField.textColor = RGB(68, 68, 68);
    textField.textAlignment = NSTextAlignmentLeft;
    textField.returnKeyType = UIReturnKeyDone;
    textField.keyboardType = type;
    [textField setValue:RGB(177, 177, 177) forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
    
}


-(void)setFooter:(UIButton *)btn{
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitle:@"添加银行卡" forState:UIControlStateNormal];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    [btn setBackgroundImage:[UIImage imageNamed:@"Button_Determine"] forState:UIControlStateNormal];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    btn.layer.cornerRadius=10.0;
    btn.clipsToBounds=YES;
    
}


-(void)textFieldDidChange:(UITextField *)textField{
    //卡号
    if (textField.tag==10003) {
        
    }else if (textField.tag==10002){
        
        textField.text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];

    }
    
}



#pragma mark-银行卡号校验
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField text];
    
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, 4)];
    }
    
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    
    if (newString.length >= 24) {
        return NO;
    }
    
    [textField setText:newString];
    
    return NO;
}
#pragma mark - gesture actions
- (void)closeKeyboard
//- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer
{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64, G_SCREENWIDTH,0.0);
    } completion:^(BOOL finished) {
        
    }];

}

- (void)keyboardWillShow:(NSNotification *)noti
{
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64, G_SCREENWIDTH,0.0);
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark-添加银行卡
- (void)addBtnClick{
    [self.view endEditing:YES];
    
    if (_UserRealName.length>0) {
        
    }else{
        //姓名判断
        if (!_nameTF.text||[_nameTF.text isEqualToString:@""]) {
            [SVProgressHUD showErrorWithStatus:@"请输入姓名！"];
            return;
        }
    }
    
    
    if (!_bankModel.bankId) {
        [SVProgressHUD showErrorWithStatus:@"请选择银行！"];
        return;
    }
    
    if (!_bankModel.provinceId) {
        [SVProgressHUD showErrorWithStatus:@"请选择省份！"];
        return;
    }
    
    if (!_bankModel.cityId) {
        [SVProgressHUD showErrorWithStatus:@"请选择市区！"];
        return;
    }
    

    NSString *bankName=@"";
    if (!_bankNameTf.text||[_bankNameTf.text isEqualToString:@""]) {
//        [SVProgressHUD showErrorWithStatus:@"请输入支行名称！"];
//        return;
    }else{
        bankName=_bankNameTf.text;
    }
    
    if (!_cardNumTf.text||[_cardNumTf.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入银行卡号！"];
        return;
    }
    if (_nameTF.text.length>0) {
        _bankModel.userName=_nameTF.text;
    }else{
        _bankModel.userName=_UserRealName;
    }
    
    _bankModel.subBankName=bankName;
    _bankModel.bankNumer=[_cardNumTf.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    MCMineInfoModel * mineInfoModel=[MCMineInfoModel sharedMCMineInfoModel];
    
    NSString * UserName;
    if (mineInfoModel.UserNickName.length>1) {
        UserName=mineInfoModel.UserNickName;
    }else{
        UserName=[[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"];
    }
    NSDictionary * dic=
    @{
      @"UserName":UserName,
      @"RealName":_bankModel.userName,
      @"UserID":[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"],
      @"BankCode":_bankModel.bankId,//银行编码
      @"CardNumber":_bankModel.bankNumer,//银行卡号
      @"Province":_bankModel.provinceId,//所在省份
      @"City":_bankModel.cityId,//所在市级
      @"BranchName":_bankModel.subBankName//支行名称（非必填时可传空）
      
      };
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"提示内容" preferredStyle:UIAlertControllerStyleAlert];

 
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:@"提示"];
    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:RGB(0, 0, 0) range:NSMakeRange(0, 2)];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 2)];
    [alertController setValue:alertControllerStr forKey:@"attributedTitle"];
    
    //修改message
    NSString * userName=[NSString stringWithFormat:@"%@**",[_bankModel.userName substringToIndex:1]];
    
    NSString * message;
    if (_bankNameTf.text&&(_bankNameTf.text.length>0)) {
        
        
        message=[NSString stringWithFormat:@"\n持卡人姓名：%@\n开户银行：%@\n支行：%@\n卡号：%@\n开户地址：%@-%@\n",userName,_bankModel.bankName,_bankModel.subBankName,_bankModel.bankNumer,_bankModel.provinceName,_bankModel.cityName];
        
    }else{
        
        message=[NSString stringWithFormat:@"\n持卡人姓名：%@\n开户银行：%@\n卡号：%@\n开户地址：%@-%@\n",userName,_bankModel.bankName,_bankModel.bankNumer,_bankModel.provinceName,_bankModel.cityName];
    }
    
    
    NSRange range1 = [message rangeOfString:userName];
    NSRange range2 = [message rangeOfString:_bankModel.subBankName];
    NSRange range3 = [message rangeOfString:_bankModel.bankNumer];
    NSRange range4 = [message rangeOfString:[NSString stringWithFormat:@"%@-%@",_bankModel.provinceName,_bankModel.cityName]];
    
    NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:message];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    [alertControllerMessageStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, alertControllerMessageStr.length)];

    
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:RGB(69, 142, 226) range:range1];
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:RGB(69, 142, 226) range:range2];
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:RGB(69, 142, 226) range:range3];
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:RGB(69, 142, 226) range:range4];
    
    [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, message.length)];
    [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MCAddBankCardModel  * apiModel =[[MCAddBankCardModel alloc]initWithDic:dic];
        self.apiModel=apiModel;
        [apiModel refreashDataAndShow];
        apiModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        };
        apiModel.callBackSuccessBlock = ^(id manager) {
            if (self.type==NOPasswordAndNOCard) {
                [self refreshData];
                MCPasswordSettingViewController * vc =[[MCPasswordSettingViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                if (self.block) {
                    self.block(_bankModel);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
        };
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];

    [self presentViewController:alertController animated:YES completion:nil];
    
    
   
}


#pragma mark-省份选择
- (void)shengSelectedBtnClick{

    [self.view endEditing:YES];
    [_bottomView reloadDataWithType:ProvinceType andModel:_bankModel];
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64-HEIGHT_MCSBVIEW, G_SCREENWIDTH,HEIGHT_MCSBVIEW);
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark-市区选择
- (void)citySelectedBtnClick{
    
    if ([_bankModel.provinceName isEqualToString:@""]||!_bankModel.provinceName) {
        [SVProgressHUD showErrorWithStatus:@"请先选择省份！"];
        return;
    }
    [self.view endEditing:YES];
    [_bottomView reloadDataWithType:CityType andModel:_bankModel];
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64-HEIGHT_MCSBVIEW, G_SCREENWIDTH,HEIGHT_MCSBVIEW);
    } completion:^(BOOL finished) {
        
    }];
    
}
#pragma mark-银行选择
- (void)bankSelectedBtnClick{
    [self.view endEditing:YES];
    [_bottomView reloadDataWithType:BankType andModel:_bankModel];
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64-HEIGHT_MCSBVIEW, G_SCREENWIDTH,HEIGHT_MCSBVIEW);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
}

#pragma mark=======MCSelectedBottomDelegate==========
/*
 * 选择省份
 */
-(void)MCSelectedBottom_Province:(MCBankModel *)model{
    
    _bankModel.provinceName=model.provinceName;
    _bankModel.provinceId=model.provinceId;
    
    //市区重置
    _bankModel.cityName=nil;
    _bankModel.cityId=nil;

    [_shengSelectedBtn setTitle:model.provinceName forState:UIControlStateNormal];
    [_citySelectedBtn setTitle:@"请选择市区 >" forState:UIControlStateNormal];
    
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64, G_SCREENWIDTH,0.0);
    } completion:^(BOOL finished) {
        
    }];
    

}

/*
 * 选择市区
 */
-(void)MCSelectedBottom_City:(MCBankModel *)model{
    _bankModel.cityName=model.cityName;
    _bankModel.cityId=model.cityId;
    [_citySelectedBtn setTitle:model.cityName forState:UIControlStateNormal];
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64, G_SCREENWIDTH,0.0);
    } completion:^(BOOL finished) {
        
    }];
    
}

/*
 * 选择银行
 */
-(void)MCSelectedBottom_Bank:(MCBankModel *)model{
    _bankModel.bankName=model.bankName;
    _bankModel.bankLogo=model.bankLogo;
    _bankModel.bankId=model.bankId;
    
    [_bankSelectedBtn setTitle:model.bankName forState:UIControlStateNormal];
    [UIView animateWithDuration:0.2 animations:^{
        _bottomView.frame=CGRectMake(0, G_SCREENHEIGHT-64, G_SCREENWIDTH,0.0);
    } completion:^(BOOL finished) {
        
    }];
}
-(void)refreshData{
    __weak __typeof(self)wself = self;
    
    MCMineInfoModel *mineInfoModel = [MCMineInfoModel sharedMCMineInfoModel];
    self.mineInfoModel = mineInfoModel;
    
    [mineInfoModel refreashDataAndShow];
    mineInfoModel.callBackSuccessBlock = ^(id manager) {
        
        wself.mineInfoModel=[MCMineInfoModel mj_objectWithKeyValues:manager];
        
    };
    
    
    
    
}
@end






































